package com.example.myactspringboot.util;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;

/**
 * @Create 2023-09-24 09:46
 * @Description
 */
public class TimeFormatKeyGenerator {

    private static volatile int loopCount = 0;
    private int pid = getProcessID();
    protected Random random = new SecureRandom();
    private static TimeFormatKeyGenerator timeFormatKeyGenerator;


    private TimeFormatKeyGenerator() {
//        this.random.setSeed((new Date()).getTime());
    }
    public static TimeFormatKeyGenerator getInstance(){
        if (timeFormatKeyGenerator == null){
            synchronized (TimeFormatKeyGenerator.class){
                if (timeFormatKeyGenerator == null){
                    timeFormatKeyGenerator = new TimeFormatKeyGenerator();
                }
            }
        }
        timeFormatKeyGenerator.random.setSeed((new Date()).getTime());
        return timeFormatKeyGenerator;
    }
    protected static final int getProcessID() {

        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        return Integer.valueOf(runtimeMXBean.getName().split("@")[0]);
    }

    public String getNext(String type) {
        return this.getTimeString() + this.getRandomNumber();
    }

    public String getNext() {
        return this.getTimeString() + this.getRandomNumber();
    }

    protected String getTimeString() {
        return DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
    }

    protected String getRandomNumber() {
        loopCount = loopCount + 1 > 9999 ? 0 : loopCount + 1;
        return String.format("%04d", loopCount) + String.format("%03d", Thread.currentThread().getId()) + String.format("%02d", this.random.nextInt(100));
    }
}
